package se.teamscape.client.presenter;

import java.util.ArrayList;

import net.customware.gwt.presenter.client.EventBus;
import se.teamscape.client.rpc.CachingDispatchAsync;
import se.teamscape.client.rpc.DispatchCallback;
import se.teamscape.client.utils.NameValuePair;
import se.teamscape.shared.model.Person;
import se.teamscape.shared.rpc.GetModel;
import se.teamscape.shared.rpc.GetModelResult;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.inject.Inject;

/**
 * Presenter for editing a Person model
 * 
 * @author Andreas Borglin
 * 
 */
public class EditPersonPresenter extends EditDataPresenter {

    private final CachingDispatchAsync mDispatcher;

    @Inject
    public EditPersonPresenter(Display display, EventBus eventBus, CachingDispatchAsync dispatcher) {
        super(display, eventBus);
        this.mDispatcher = dispatcher;
    }

    @Override
    protected void onLazyBind() {

        registerHandler(display.getSave().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                // FIXME
                Window.alert("Edit not implemented");
            }
        }));

        registerHandler(display.getCancel().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                // FIXME
                Window.alert("Edit not implemented");
            }
        }));

    }

    private void updateData(String id) {

        // fetch Person from server/cache
        // It is very likely that it resides in cache at this point
        mDispatcher.executeWithCache(new GetModel(id, Person.class.getName()), new DispatchCallback<GetModelResult>() {
            @Override
            public void callback(GetModelResult result) {
                Person person = (Person) result.getModel();
                ArrayList<NameValuePair<String>> list = Person.getAsList(person);
                display.setData(list);
                viewUpdated();
            }
        });
    }

    @Override
    protected void onRevealDisplay() {

        if (needsUpdate()) {
            updateData(getId());
        }

    }
}
